class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Java1016 {
    ListNode head;
    public void creat() {

        ListNode x1 = new ListNode(12);
        ListNode x2 = new ListNode(23);
        ListNode x3 = new ListNode(34);
        ListNode x4 = new ListNode(45);


        x1.next = x2;
        x2.next = x3;
        x3.next = x4;

        head = x1;
    }

    public ListNode reverseList() {
        if(head == null){
        return head;
    }
        ListNode cur = head.next;

        //后面的节点23、34、45通过反转算法重新连接成了新链表，
        // 但类的head字段没有更新，仍然指向这个孤立的节点12
        head.next = null;

        while (cur != null) {
            ListNode curN = cur.next;
            cur.next = head;
            head = cur;
            cur = curN;
        }
        return head;
    }

    public void show() {

        ListNode z = head;

        while (z != null) {
            System.out.print(z.val + " ");
            z = z.next;
        }
    }

    public void show(ListNode newhead) {

        ListNode z = newhead;

        while (z != null) {
            System.out.print(z.val + " ");
            z = z.next;
        }
    }


    public static void main (String[]args){
        Java1016 y = new Java1016();

        y.creat();
        y.show();

        //关键点，没有及时更新head值的话，导致show方法中head还是指向类的head
        //假如将head设置为ListNode的成员变量的话就可以跳过更新head这个操作了
        //y.head = y.reverseList(y.head);

        System.out.println();

        //或者定义第二个带有newhead参数的show方法来解决
        y.show(y.reverseList());

    }

}
